package com.app.controller;

//import com.imooc.grace.result.GraceJSONResult;
import com.app.bo.RegistLoginBO;
import com.app.grace.result.GraceJSONResult;
import com.app.pojo.Users;
import com.app.service.UserService;
import com.app.utils.IPUtil;
import com.app.utils.SMSUtils;
import com.app.utils.ValidateCodeUtils;
import com.app.vo.UsersVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Api(tags = "PassportController 短信接口模块")
@RequestMapping("passport")
@RestController
//public class PassportController{
public class PassportController extends BaseController{
    ///passport/getSMSCode?mobile=" + mobile,
//@Autowired
//private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    /**
     * 发送手机验证码
     * @return
     */
    @PostMapping("getSMSCode")
    public GraceJSONResult getSMSCode(@RequestParam String mobile, HttpSession session,
                                      HttpServletRequest request){
        if (StringUtils.isNotEmpty(mobile)){ //判断手机号是否为空

            //获取用于ip地址
            String userIp = IPUtil.getRequestIp(request);
            // 根据用户ip进行限制，限制用户在60秒之内只能获得一次验证码
            //redis.setnx60s(MOBILE_SMSCODE + ":" + userIp, userIp);
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code验证码={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",mobile,code);
            //需要将生成的验证码保存到Session
            session.setAttribute(mobile,code);

            //把验证码放入redis中  限时30分钟
            redis.set(MOBILE_SMSCODE + ":" + mobile, code, 30 * 60);

//            return "手机验证码发送成功";
            return GraceJSONResult.ok("消息发送成功");
        }
//        return "短信发送失败";
        return GraceJSONResult.errorMsg("消息发送失败");
    }
    @PostMapping("login")
    public GraceJSONResult login(@Valid @RequestBody RegistLoginBO registLoginBO,
                                 BindingResult result,
                                 HttpServletRequest request)throws Exception{
        //判断BindingResult中是否保存了错误的验证信息，如果有，则需要返回到前端
        if (result.hasErrors()){
            Map<String,String> map = getErrors(result);
            return GraceJSONResult.errorMap(map);
        }
        String mobile = registLoginBO.getMobile();
        String code = registLoginBO.getVerifyCode();

        //1.查询数据库，判断用户是否存在
        Users user = userService.queryMobileIsExist(mobile);
        if (user == null){
            user = userService.createUser(mobile);
        }
        //如果不为空，可以继续下方业务，可以保存用户信息和会话信息
        String uToken = UUID.randomUUID().toString();

        //返回用户信息
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user,usersVO);
        usersVO.setUserToken(uToken);
        return GraceJSONResult.ok(usersVO);
    }

    @PostMapping("logout")
    public GraceJSONResult logout(@RequestParam String userId,
                                  HttpServletRequest request) throws Exception {

        // 后端只需要清除用户的token信息即可，前端也需要清除，清除本地app中的用户信息和token会话信息
//        redis.del(REDIS_USER_TOKEN + ":" + userId);

        return GraceJSONResult.ok();
    }

    public Map<String,String> getErrors(BindingResult result){
        Map<String,String>  map = new HashMap<>();
        List<FieldError> errorList = (List<FieldError>) result.getFieldError();
        for (FieldError ff : errorList){
            //错误所对应的属性字段名
            String field =   ff.getField();
            //错误的信息
            String msg = ff.getDefaultMessage();
            map.put(field,msg);
        }
        return map;
    }

}
